//
//  MoviePlayer.m
//  movie
//
//  Created by MyMac on 15/4/12.
//  Copyright (c) 2015年 MyMac. All rights reserved.
//

#import "MoviePlayer.h"

@interface MoviePlayer()

@property(nonatomic,strong)UIProgressView*progressLoad;
@property(nonatomic,strong)UISlider*sliderPlay;

@end
@implementation MoviePlayer
-(id)initWithFrame:(CGRect)frame
{
    if ([super initWithFrame:frame]) {
        UIButton*quickBtn=[[UIButton alloc]initWithFrame:CGRectMake(100, 30, 40, 20)];
        quickBtn.backgroundColor=[UIColor grayColor];
        [quickBtn addTarget:self action:@selector(quickClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:quickBtn];
    self.progressLoad=[[UIProgressView alloc]initWithFrame:CGRectMake(0,10,frame.size.width,10)];
    self.progressLoad.progressTintColor=[UIColor redColor];
//  self.progress.trackTintColor=[UIColor blackColor];
    [self addSubview:self.progressLoad];
        
        self.sliderPlay=[[UISlider alloc]initWithFrame:CGRectMake(0,10,frame.size.width,10)];
        self.sliderPlay.userInteractionEnabled=YES;
        [self.progressLoad addSubview:self.sliderPlay];
        
        
    AVPlayerLayer*player=[AVPlayerLayer playerLayerWithPlayer:self.player];
    
    player.frame=CGRectMake(0, 100, frame.size.width, frame.size.height-200);
        [self.layer addSublayer:player];
    player.backgroundColor=[[UIColor yellowColor] CGColor];
    UIButton*btn=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn setTitle:@"开始" forState:UIControlStateNormal];
    [btn setTitle:@"暂停" forState:UIControlStateSelected];
    [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    btn.frame=CGRectMake(10,40, 40, 20);
    [self addSubview:btn];
    }
    return self;
    
  

}
-(void)quickClick:(UIButton*)btn
  {
      [self.player seekToTime:CMTimeMake(200, 1)];
 // [self.player seekToTime:CMTimeMake(200.0, 100.0) completionHandler:^(BOOL finished) {
      
//      NSLog(@"^^^^^^^^^^^^^^^^^^^^^%ld",(long)finished);
//  }];
  
  
  
  }
-(void)btnClick:(UIButton*)btn
{
    btn.selected=!btn.selected;
    if (btn.selected==YES) {
        [self.player pause];
    }else
        [self.player play];
    
    
}
-(void)addProgressObserver{
    AVPlayerItem *playerItem=self.player.currentItem;//当前的item，即当前的视频
    
    //这里设置每秒执行一次
    __block  UISlider*p=self.sliderPlay;
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current=CMTimeGetSeconds(time);
        float total=CMTimeGetSeconds([playerItem duration]);
        NSLog(@"当前已经播放%.2fs.",current);
        if (current) {
            p.value=current/total;
            NSLog(@"%ld",(long)p.value);
        }
    }];
}


-(AVPlayer*)player
{
    if(!_player){
        AVPlayerItem*playerItem=[AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4"]];//AVPlayerItem一个媒体资源管理对象，管理着媒体视频的状态，信息，一个AVPlayerItem对应一个视频资源
        
        _player=[AVPlayer playerWithPlayerItem:playerItem];
        
        [self addPlayerFinishedNotifacation];
        [self addProgressObserver];
        [self addObserverToPlayerItem:playerItem];
        
    }
    return _player;
    
}
-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem{
    //监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //监控网络加载情况属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    AVPlayerItem *playerItem=object;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status= [[change objectForKey:@"new"] intValue];
        if(status==AVPlayerStatusReadyToPlay){
            NSLog(@"正在播放...，视频总长度:%.2f",CMTimeGetSeconds(playerItem.duration));
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"]){
        NSArray *array=playerItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓冲时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);//从哪开始缓冲的，
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);//从这个开始的缓冲点，缓冲到哪了
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;//缓冲总长度
        [self.progressLoad setProgress:totalBuffer/CMTimeGetSeconds(self.player.currentItem.duration)];
        NSLog(@"共缓冲：%.2f",totalBuffer);
        //
    }
}
-(void)addPlayerFinishedNotifacation
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playerFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    //AVPlayerItem控制视频播放状态，所以通知是AVPlayerItem
    
    
    
}
-(void)playerFinished
{
    NSLog(@"视频播放完成");
    
    
}
@end
